// 单例模式

package singleton

import "sync"

/********** 懒汉模式，非线程安全 **********/
type LasySingleton struct{}

//建立私有变量
var instance *LasySingleton

//获取单例对象的方法，引用传递返回
func GetInstance() *LasySingleton {
	if instance == nil {
		instance = new(LasySingleton)
	}
	return instance
}

/********** 懒汉模式，线程安全 **********/
type SafeSingleton struct{}

var safeInstance *SafeSingleton
var once sync.Once

func GetSafeInstance() *SafeSingleton {
	once.Do(func() {
		safeInstance = new(SafeSingleton)
	})
	return safeInstance
}

/********** 饿汉模式，线程安全 **********/
type HungrySingleton struct{}

var hungrySingleton *HungrySingleton = new(HungrySingleton)

func GetHungrySingleton() *HungrySingleton {
	return hungrySingleton
}

/*
func main() {
	// 懒汉模式，非线程安全
	instance1 := GetInstance()
	instance2 := GetInstance()
	if instance1 == instance2 {
		println("instance1 == instance2")
	}

	// 懒汉模式，线程安全
	instance3 := GetSafeInstance()
	instance4 := GetSafeInstance()
	if instance3 == instance4 {
		println("instance3 == instance4")
	}

	// 饿汉模式，线程安全
	instance5 := GetHungrySingleton()
	instance6 := GetHungrySingleton()
	if instance5 == instance6 {
		println("instance5 == instance6")
	}
}
*/
